package org.jeecg.modules.scm.common.util;


import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Map;

public class HttpRequest {

    @Autowired
    static RestTemplate restTemplate = new RestTemplate();

    //图片url转base64
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        // BASE64Encoder encoder = new BASE64Encoder();
        return "";//encoder.encode(data);
    }

    //MultipartFile转File
    public static File MultipartFileToFile(MultipartFile multipartFile) {
        //        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            file = new File(multipartFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
            file.deleteOnExit();
        } catch (Exception e) {
            throw new JeecgBootException("MultipartFile转File失败");
        }
        return file;
    }

    //向指定url传递图片并返回响应
    public static Map PostRequestFile(String url, MultipartFile params){

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        //设置请求体
        File file = MultipartFileToFile(params);

        if(file!=null){
            FileSystemResource fileSystemResource = new FileSystemResource(new File(file.getPath()));
            MultiValueMap<String, Object> files = new LinkedMultiValueMap<>();
            files.add("file", fileSystemResource);
//            files.add("money",6676);
            //用HttpEntity封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(files,headers);
            //服务端返回的json格式："
            String result = restTemplate.postForObject(url, request, String.class);
            //将服务端发送过来的json转换成map
            Map mapTypes = JSON.parseObject(result);
//            System.out.println(mapTypes);
            return mapTypes;
        }

        return null;
    }
    //向指定url发送对象信息
    public static<T> void PostInfomation(String url,T obj){
        //url = "http://jsonplaceholder.typicode.com/posts";
        //设置请求头
        //HttpHeaders headers = new HttpHeaders();
        //设置请求体
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("data",JSON.toJSON(obj));
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(params,headers);
        String s = restTemplate.postForObject(url, request, String.class);
        System.out.println(s);
        //System.out.println(res);
    }
    //向指定url发送封装信息
    public static String PostInfomation(String url,MultiValueMap<String, Object> param){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(param,headers);
        String s = restTemplate.postForObject(url, request, String.class);
        return s;
    }
    //从minio 的test 获取object并转化为StreamResource
    public static InputStreamResource getStreamResource(String url){
        InputStreamResource inputStreamResource = null;
        try{
            InputStream minioFile = MinioUtil.getMinioFile(MinioUtil.getBucketName(), url);
            int available = minioFile.available();
            //直接使用InputStramResource方法会报错
            inputStreamResource = new InputStreamResource(minioFile){
                @Override
                public long contentLength(){
                    return available==0?1:available;
                }

                @Override
                public String getFilename(){
                    return url.substring(
                            url.lastIndexOf("\\")>0?url.lastIndexOf("\\"):url.lastIndexOf("/")
                                    +1);
                }
            };
        }
        catch (Exception e){
            throw new JeecgBootException("获取文件resource失败");
        }
        return inputStreamResource;
    }
    //将inpustream转化为本地文件，测试用
    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        input.close();
        downloadFile.close();

    }

    public static void main(String[] args) throws IOException {
//        ScmCusInfo scmCusInfo = new ScmCusInfo();
//        scmCusInfo.setCusNo(888);
//        System.out.println(scmCusInfo);
////        PostInfomation("http://localhost:9999/jeecg-scm/test/jeecg/test",scmCusInfo);
//        System.out.println(JSON.toJSON("可以"));
//        downLoadFile("http://212.64.69.165:9000/test/contractTemplate/6.png");
//        MinioUtil.setMinioUrl("http://212.64.69.165:9000/");
//        MinioUtil.setBucketName("test");
//        MinioUtil.setMinioName("root");
//        MinioUtil.setMinioPass("hryl123456+");


    }


}
